import { ElMessage, ElMessageBox } from "element-plus";
import { store } from "../index.js";
import { defineStore } from "pinia";
import { useDetectionStoreHook } from "./detection.js";
import { toRaw } from "vue";

export const useProcessStore = defineStore("process", {
  state: () => ({
    processes: [], // 可选工序列表
    process: null, // 当前工序模板id，用于获取量仪模板配置
    processSrc: null, // 当前工序id，用于查询工艺要求
    processName: "", // 当前工序名称
    technicParams: [], // 工艺要求

    doingModels: [], // 当前产线生产中订单的所有物料型号集合
    partType: "", // 当前加工零件类型
    modelIndex: 0, // 当前所选型号的索引

    workCenters: [], // 加工中心可选列表
    workSiteId: null, // 作业单元编号
    workCenterType: null, // 加工中心类型
    workCenterId: null, // 产线编号
    workCenterDesc: "" // 产线名称描述
  }),
  getters: {
    // 当前型号的物料编码
    modelCode() {
      return this.doingModels[this.modelIndex]?.partCode;
    },
    // 当前型号物料名称
    modelName() {
      return this.doingModels[this.modelIndex]?.partName;
    },
    workSites() {
      const uniqueMap = new Map();
      return this.workCenters.filter(
        (item) =>
          item.WorkSiteID && !uniqueMap.has(item.WorkSiteID) && uniqueMap.set(item.WorkSiteID, 1)
      );
    },
    workCenterTypes() {
      const uniqueMap = new Map();
      return this.workCenters?.filter(
        (item) =>
          item.WorkCenterType &&
          !uniqueMap.has(item.WorkCenterType) &&
          item.WorkSiteID === this.workSiteId &&
          uniqueMap.set(item.WorkCenterType, 1)
      );
    },
    workCenterIds() {
      const uniqueMap = new Map();
      return this.workCenters?.filter(
        (item) =>
          item.WorkCenterID &&
          !uniqueMap.has(item.WorkCenterID) &&
          item.WorkCenterType === this.workCenterType &&
          uniqueMap.set(item.WorkCenterID, 1)
      );
    }
  },
  actions: {
    // 获取历史配置
    async defaultSetup() {
      this.workCenterId = await window.api.getStore("workCenterId");
      this.workCenterDesc = await window.api.getStore("workCenterDesc");
      this.workCenterType = await window.api.getStore("workCenterType");
      this.processes = await window.api.getStore("processes");
      this.process = await window.api.getStore("process");
      // this.processSrc = await window.api.getStore("processSrc");
      // this.processName = await window.api.getStore("processName");
      if (this.workCenterId && this.workCenterType) {
        await this.getProcesses();
        await this.getPartModels();
      }
      this.modelIndex = await window.api.getStore("modelIndex");
      // const fieldsBuff = await window.api.getStore("fields");
      // const detectionStore = useDetectionStoreHook();
      // if (fieldsBuff) {
      //   detectionStore.setFields(JSON.parse(fieldsBuff));
      // }
      await this.setProcess(this.process);
      // await detectionStore.updateDataset();
      await this.getTechnicParams();
    },
    // 获取加工中心的所有可选项
    async getWorkCenterOptions() {
      const res = await window.api.getWorkCenters();
      if (res.code === 0) {
        this.workCenters = res.data;
      }
      return res;
    },
    async getProcesses() {
      if (!this.workCenterType) {
        ElMessage.error("请先选择产线再进行工序选择！");
        return;
      }
      const res = await window.api.getProcessInfo(this.workCenterType);
      if (res.code === 0) {
        this.processes = res.data.map((d) => {
          return { ...d, label: d.template, value: d.id };
        });
        await window.api.setStore("processes", toRaw(this.processes));
      } else {
        this.processes = await window.api.getStore("processes");
      }
      return res;
    },
    async getPartModels() {
      if (this.workCenterId) {
        const res = await window.api.getPartModelList(this.workCenterId);
        if (res.code === 0) {
          this.doingModels = res.data;
          if (this.modelIndex >= this.doingModels.length) {
            this.modelIndex = 0;
          }
        } else {
          this.doingModels = [];
        }
        return res;
      } else {
        return {
          code: 10,
          msg: "零件型号获取失败！请先选择岗位信息！",
          data: []
        };
      }
    },
    // 获取工艺要求的数据
    async getTechnicParams() {
      if (this.modelCode && this.processSrc) {
        const res = await window.api.getTechnicParams(this.processSrc, this.modelCode);
        if (res.code === 0) {
          const detectFields = useDetectionStoreHook()
            .fields.filter((f) => f.method === 0)
            .map((f) => f.name);
          const resFields = res.data.map((d) => d.name);
          this.technicParams = {};
          if (
            (resFields.length < detectFields.length ||
              !detectFields.every((f) => resFields.indexOf(f) !== -1)) &&
            detectFields.length !== 0
          ) {
            ElMessageBox.confirm(
              "该岗位查无相关型号的工艺要求，请联系工艺技术员完善信息！",
              "工艺要求缺失",
              {
                type: "warning",
                showCancelButton: false
              }
            );
          }
          res.data.forEach((d) => {
            this.technicParams[d.name] = { ...d };
          });
        } else {
          console.log(res.data);
          return res;
        }
      }
    },
    async getShortCode() {
      const res = await window.api.getModelShortCode(this.modelCode);
      if (res.code === 0 && res.data) {
        return res.data;
      } else {
        return "无";
      }
    },
    modelIndexInc(inc) {
      const maxIndex = this.doingModels.length - 1;
      const nowIndex = this.modelIndex;
      const newIndex = nowIndex + inc;
      if (newIndex < 0) {
        this.setModelIndex(maxIndex + newIndex + 1);
      } else if (newIndex > maxIndex) {
        this.setModelIndex(newIndex - maxIndex - 1);
      } else {
        this.setModelIndex(this.modelIndex + inc);
      }
      this.getTechnicParams();
    },
    setModelIndex(index) {
      this.modelIndex = index;
      window.api.setStore("modelIndex", index);
    },
    async setWorkCenter(workCenterId, workCenterDesc) {
      this.workCenterId = workCenterId;
      this.workCenterDesc = workCenterDesc;
      await window.api.setStore("workCenterId", workCenterId);
      await window.api.setStore("workCenterDesc", workCenterDesc);
      await window.api.setStore("workCenterType", this.workCenterType);
      await this.getProcesses();
      if (this.processes.length > 0) {
        await this.setProcess(this.processes[0].id);
      }
      await this.getPartModels();
      if (this.doingModels.length > 0) {
        this.modelIndex = 0;
      }
      await this.getTechnicParams();
    },
    async setProcess(process) {
      this.process = process;
      this.processName = undefined;
      this.processSrc = undefined;
      let templateId = undefined;
      for (let i = 0; i < this.processes.length; i++) {
        if (this.processes[i].id === this.process) {
          this.processName = this.processes[i].template;
          this.processSrc = this.processes[i].process_id;
          templateId = this.processes[i].id;
          break;
        }
      }
      await window.api.setStore("process", this.process);
      await window.api.setStore("processSrc", this.processSrc);
      await window.api.setStore("processName", this.processName);
      const detectionStore = useDetectionStoreHook();
      let fields = [];
      if (templateId !== undefined) {
        const res = await window.api.getProcessInfo(this.workCenterType, templateId);
        if (res.code === 0) {
          fields = res.data.fields;
          // await window.api.setStore("fields", JSON.stringify(fields));
        } else {
          // 查找当前工序，找出符合的工序字段
          for (let i = 0; i < this.processes.length; i++) {
            const process = this.processes[i];
            if (process.process_id === this.processSrc) {
              fields = process.fields;
              break;
            }
          }
        }
      }
      detectionStore.setFields(fields);
      await detectionStore.updateDataset();
    }
  }
});

export function useProcessStoreHook() {
  return useProcessStore(store);
}
